package com.imooc.controller.manage;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.imooc.entity.Book;
import com.imooc.entity.Category;
import com.imooc.exception.BusinessException;
import com.imooc.exception.BusinessExceptionCode;
import com.imooc.service.BookService;
import com.imooc.service.CategoryService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/management/book")
public class ManageBookController {
    @Resource
    private CategoryService categoryService;

    @Resource
    private BookService bookService;

    @GetMapping("/index.html")
    public ModelAndView showBook() {
        ModelAndView modelAndView = new ModelAndView("/management/book");
        List<Category> categories = categoryService.selectAll();
        modelAndView.addObject("categories", categories);
        return modelAndView;
    }

    @GetMapping("/list")
    @ResponseBody
    public Map<String, Object> books(Integer page, Integer limit)
    {
        if (page == null) page = 1;
        if (limit == null) limit = 10;
        IPage<Book> bookIPage = bookService.paging(null, null, page, limit);
        Map<String, Object> result = new HashMap<>();
        result.put("code", 0);
        result.put("msg", "success");
        result.put("data", bookIPage.getRecords()); // 当前页面数据
        result.put("count", bookIPage.getTotal()); // 为分页时记录总数
        return result;
    }

    @PostMapping("/upload")
    @ResponseBody
    public Map<String, Object> upload(@RequestParam("img") MultipartFile file, HttpServletRequest request) throws IOException {
        Map<String, Object> result = new HashMap<>();
        String uploadPath = request.getServletContext().getResource("/").getPath() + "/upload/";
        String fileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        file.transferTo(new File(uploadPath + fileName + suffix));
        result.put("errno", 0);
        result.put("data", new String[]{"/upload/" + fileName + suffix});
        return result;
    }

    @PostMapping("/create")
    @ResponseBody
    public Map<String, Object> createBook(Book book) {
        Map<String, Object> result = new HashMap<>();
        try {
            book.setEvaluationScore(0f);
            book.setEvaluationQuantity(0);
            String description = book.getDescription();
            Document document = Jsoup.parse(description);
            Element imgElement = document.selectFirst("img");
            if (imgElement != null) {
                String cover = imgElement.attr("src");
                book.setCover(cover);
            }
            bookService.createBook(book);
            result.put("code", 0);
            result.put("msg", "success");
        } catch (BusinessException ex) {
            ex.printStackTrace();
            result.put("code", ex.getCode());
            result.put("msg", ex.getMessage());
        }
        return result;
    }

    @PostMapping("/update")
    @ResponseBody
    public Map<String, Object> updateBook(Book book) {
        Map<String, Object> result = new HashMap<>();
        try {
            Book findById = bookService.getById(book.getBookId());
            if (findById == null) {
                throw new BusinessException(BusinessExceptionCode.BOOK_NOT_FOUND);
            }

            findById.setBookName(book.getBookName());
            findById.setSubTitle(book.getSubTitle());
            findById.setAuthor(book.getAuthor());
            findById.setDescription(book.getDescription());
            findById.setCategoryId(book.getCategoryId());

            String description = findById.getDescription();
            Document document = Jsoup.parse(description);
            Element imgElement = document.selectFirst("img");
            if (imgElement != null) {
                String cover = imgElement.attr("src");
                findById.setCover(cover);
            }
            bookService.updateBook(findById);
            result.put("code", 0);
            result.put("msg", "success");
        } catch (BusinessException ex) {
            ex.printStackTrace();
            result.put("code", ex.getCode());
            result.put("msg", ex.getMessage());
        }
        return result;
    }

    @GetMapping("/delete/{bookId}")
    @ResponseBody
    public Map<String, Object> deleteBook(@PathVariable("bookId") Long bookId) {
        Map<String, Object> result = new HashMap<>();
        try {
            Book book = bookService.getById(bookId);
            if (book == null) {
                throw new BusinessException(BusinessExceptionCode.BOOK_NOT_FOUND);
            }
            bookService.deleteById(bookId);
            result.put("code", 0);
            result.put("msg", "success");
        } catch (BusinessException ex) {
            ex.printStackTrace();
            result.put("code", ex.getCode());
            result.put("msg", ex.getMessage());
        }
        return result;
    }

    @GetMapping("/id/{bookId}")
    @ResponseBody
    public Map<String, Object> getBookById(@PathVariable("bookId") Long bookId) {
        Map<String, Object> result = new HashMap<>();
        try {
            Book book = bookService.getById(bookId);
            if (book == null) {
                throw new BusinessException(BusinessExceptionCode.BOOK_NOT_FOUND);
            }
            result.put("code", 0);
            result.put("msg", "success");
            result.put("data", book);
        } catch (BusinessException ex) {
            ex.printStackTrace();
            result.put("code", ex.getCode());
            result.put("msg", ex.getMessage());
        }
        return result;
    }
}
